function arrayToTreeRec(arr, parentId) {
  return arr.reduce((newArr, cur) => {
    if (cur.parentId == parentId) {
      cur.children = arrayToTreeRec(arr, cur.id);
      newArr.push(cur);
    }
    return newArr;
  }, []);
}

let source = [
  {
    id: 1,
    parentId: 0,
    name: 'body',
  },
  {
    id: 2,
    parentId: 1,
    name: 'title',
  },
  {
    id: 3,
    parentId: 2,
    name: 'div',
  },
];

console.log(arrayToTreeRec(source, 0));

console.log(arrayToTreeRec(source));
